package me.mingshan.leetcode;

/**
 * https://leetcode.cn/problems/univalued-binary-tree/description/
 *
 * 如果二叉树每个节点都具有相同的值，那么该二叉树就是单值二叉树。
 *
 * 只有给定的树是单值二叉树时，才返回 true；否则返回 false。
 *
 * @author hanjuntao
 * @date 2025/10/1 0001
 */
public class L_965_单值二叉树 {


    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(1);
        TreeNode node3 = new TreeNode(2);

        root.left = node1;
        root.right = node2;

        node1.left = node3;

        System.out.println(isUnivalTree(root));
    }

    /**
     * 递归实现
     *
     * 1. 先当前节点的值是否等于左右子节点的值，如果不相等，则返回false
     * 2. 递归判断左右子树是否单值
     *
     * @param root
     * @return
     */
    public static boolean isUnivalTree(TreeNode root) {
        if (root == null) {
            return true;
        }

        TreeNode left = root.left;
        if (left != null && left.val != root.val) {
            return false;
        }
        TreeNode right = root.right;
        if (right != null && right.val != root.val) {
            return false;
        }

        return isUnivalTree(root.left) && isUnivalTree(root.right);
    }
}
